package me.sealer.ssm.service.impl;

import lombok.extern.slf4j.Slf4j;
import me.sealer.ssm.constant.ErrorCodeConstant;
import me.sealer.ssm.mapper.PermissionMapper;
import me.sealer.ssm.mapper.RoleMapper;
import me.sealer.ssm.exception.SsmException;
import me.sealer.ssm.model.Permission;
import me.sealer.ssm.model.Role;
import me.sealer.ssm.service.PermissionService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author sealer
 * @date 2018/05/11.
 */
@Slf4j
@Service
public class PermissionServiceImpl implements PermissionService {
    private final RoleMapper roleMapper;
    private final PermissionMapper permissionMapper;

    public PermissionServiceImpl(RoleMapper roleMapper, PermissionMapper permissionMapper) {
        this.roleMapper = roleMapper;
        this.permissionMapper = permissionMapper;
    }

    @Override
    public List<Permission> getPermissionsByRoleName(String roleName) {
        Role role = roleMapper.getRoleByName(roleName);
        if (role == null) {
            throw new SsmException(ErrorCodeConstant.ROLE_ROLE_NOT_EXISTS, new Object[] {roleName});
        }
        Integer roleId = role.getId();
        List<Permission> permissions = permissionMapper.getPermissionsByRoleId(roleId);
        return permissions;
    }

    @Override
    public List<Permission> getPermissions() {
        return permissionMapper.selectByExample(null);
    }
}
